package net.takela.common.spring.mybatis.typehandler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
/**
 * @author baboy
 * create at 2023/1/22
 */
public class JsonObjectTypeHandler extends BaseTypeHandler<Object> {

	
    /**
     * 
     */
    @Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			Object parameter, JdbcType jdbcType)
			throws SQLException {
		String s = null;
		try {
			if (parameter instanceof String){
				String tmp = (String)parameter;
				if (tmp==null || !(tmp.startsWith("{") && tmp.startsWith("["))){
					s = tmp;
				}
			}
			if(s==null && parameter != null){
				ObjectMapper mapper = new ObjectMapper();
				mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
				mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
				s = mapper.writeValueAsString(parameter);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		ps.setString(i, s);
	}

	
    /**
     * 
     */
    @Override
	public Object getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String s = rs.getString(columnName);
		return getResult(s);
	}

	
    /**
     * 
     */
    @Override
	public Object getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		String s = rs.getString(columnIndex);
		return getResult(s);
	}

	
    /**
     * 
     */
    @Override
	public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String s = cs.getString(columnIndex);
		return getResult(s);
	}
    /**
     * 
     */
	public Object getResult(String s){
		if(s == null ) {
			return null;
		}
		try{
			ObjectMapper mapper = new ObjectMapper();
			Object obj = null;
			if(s.startsWith("[")){
				obj = mapper.readValue(s, ArrayList.class);
			}else if(s.startsWith("{")){
				obj = mapper.readValue(s, HashMap.class);
			}else {
				obj = s;
			}
			//Gson g = new GsonBuilder().media();
			//g.fromJson(s,s.startsWith("[")?List.class:HashMap.class);

			return obj;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
